<template>
  <div class="collect-goods-page">
    <el-card class="collect-card">
      <h2 class="page-title">货物收取</h2>
      <!-- 顶部单包裹查询 -->
      <div class="single-query-row">
        <el-input
          v-model="scanCode"
          placeholder="请输入或扫码任务包编号"
          clearable
          style="width: 260px"
          @keyup.enter="handleQuery"
        />
        <el-button type="primary" style="margin-left:12px;" @click="handleQuery" :loading="loading">查询</el-button>
      </div>
      <el-divider v-if="packageInfo">包裹信息</el-divider>
      <div v-if="packageInfo">
        <div class="package-info-row">
          <span><b>任务包编号：</b>{{ packageInfo.packageId }}</span>
          <span><b>配送区域：</b>{{ packageInfo.deliveryArea }}</span>
          <span><b>订单数量：</b>{{ packageInfo.orderCount }}</span>
          <span><b>总配送费：</b>¥{{ packageInfo.totalReward }}</span>
        </div>
        <el-table :data="packageInfo.orders" border style="margin: 18px 0;">
          <el-table-column prop="orderNumber" label="订单号" min-width="140" />
          <el-table-column prop="customerName" label="客户" min-width="100" />
          <el-table-column prop="address" label="地址" min-width="180" />
          <el-table-column prop="reward" label="配送费" min-width="80" />
          <el-table-column prop="remark" label="备注" min-width="120" />
        </el-table>
        <div style="text-align:right;">
          <el-button type="success" @click="openQrDialog(packageInfo)">确认揽收</el-button>
        </div>
      </div>
      <el-empty v-else-if="queried" description="未查询到该任务包信息" />

      <el-divider>配送中任务包</el-divider>
      <!-- 配送中任务包列表 -->
      <el-table :data="getFilteredPackages(deliveringPackages)" border style="margin: 18px 0;">
        <el-table-column prop="packageId" label="任务包编号" min-width="140" />
        <el-table-column prop="deliveryArea" label="配送区域" min-width="120" />
        <el-table-column prop="orderCount" label="订单数" min-width="80" />
        <el-table-column prop="totalReward" label="总配送费" min-width="100" />
        <el-table-column label="操作" min-width="120">
          <template #default="{ row }">
            <el-button type="success" @click="openQrDialog(row)">确认揽收</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 二维码弹窗 -->
      <el-dialog v-model="showQrDialog" title="扫码揽收二维码" width="320px" :close-on-click-modal="false">
        <div style="display:flex;flex-direction:column;align-items:center;">
          <img v-if="qrImg" :src="qrImg" alt="二维码" style="width:200px;height:200px;" />
          <div style="margin-top:12px;word-break:break-all;">{{ qrUrl }}</div>
        </div>
        <template #footer>
          <el-button @click="showQrDialog = false">关闭</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import QRCode from 'qrcode'
import { getTaskPackages, getTaskPackageDetail } from '@/assets/delivery.js'

const scanCode = ref('')
const loading = ref(false)
const packageInfo = ref(null)
const queried = ref(false)
const deliveringPackages = ref([])
const showQrDialog = ref(false)
const qrUrl = ref('')
const qrImg = ref('')

const handleQuery = async () => {
  if (!scanCode.value) {
    ElMessage.warning('请输入任务包编号')
    return
  }
  loading.value = true
  packageInfo.value = null
  queried.value = false
  try {
    const res = await getTaskPackageDetail(scanCode.value)
    if (res.data.code === 200 && res.data.data) {
      // 字段映射，保证页面字段都能正常显示
      const data = res.data.data
      packageInfo.value = {
        packageId: data.packageId,
        deliveryArea: data.destination || data.deliveryArea,
        deliveryTime: data.startTime ? data.startTime.replace('T', ' ').slice(0, 16) : '',
        estimatedDistance: data.estimatedDistance || 0,
        orderCount: data.orders ? data.orders.length : 0,
        totalReward: data.orders ? data.orders.reduce((sum, o) => sum + (o.reward || 0), 0) : 0,
        orders: data.orders || [],
        status: data.deliveryStatus
      }
      queried.value = false
    } else {
      packageInfo.value = null
      queried.value = true
    }
  } catch (e) {
    ElMessage.error('查询失败')
    packageInfo.value = null
    queried.value = true
  } finally {
    loading.value = false
  }
}

const fetchDeliveringPackages = async () => {
  try {
    const res = await getTaskPackages({ status: 'delivering' })
    if (res.data.code === 200 && res.data.data) {
      deliveringPackages.value = res.data.data.records || []
    } else {
      deliveringPackages.value = []
    }
  } catch (e) {
    ElMessage.error('获取配送中任务包失败')
    deliveringPackages.value = []
  }
}

// 存储已揽收包ID到localStorage
const saveCollectedPackageId = (packageId) => {
  let collected = JSON.parse(localStorage.getItem('collectedPackages') || '[]')
  if (!collected.includes(packageId)) {
    collected.push(packageId)
    localStorage.setItem('collectedPackages', JSON.stringify(collected))
  }
}

// 过滤未揽收包
const getFilteredPackages = (packages) => {
  const collected = JSON.parse(localStorage.getItem('collectedPackages') || '[]')
  return packages.filter(pkg => !collected.includes(pkg.packageId))
}

const openQrDialog = async (row) => {
  qrUrl.value = `${window.location.origin}/mobile/confirm?packageId=${row.packageId}`
  qrImg.value = ''
  try {
    qrImg.value = await QRCode.toDataURL(qrUrl.value, { width: 200, margin: 2 })
  } catch (e) {
    ElMessage.error('二维码生成失败')
  }
  showQrDialog.value = true
}

// 监听扫码确认揽收成功的消息
const handleCollectedSuccess = () => {
  showQrDialog.value = false
  fetchDeliveringPackages()
}

onMounted(() => {
  fetchDeliveringPackages()
  window.addEventListener('message', (e) => {
    if (e.data === 'collected-success') {
      handleCollectedSuccess()
    }
  })
})
onUnmounted(() => {
  window.removeEventListener('message', () => {})
})
</script>

<style scoped>
.collect-goods-page {
  padding: 32px 24px;
  background: #f7f8fa;
  min-height: 100vh;
}
.collect-card {
  max-width: 900px;
  margin: 0 auto;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0,0,0,0.06);
  padding: 32px 36px;
}
.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 18px;
}
.single-query-row {
  display: flex;
  align-items: center;
  margin-bottom: 18px;
}
.package-info-row {
  display: flex;
  gap: 32px;
  margin-bottom: 10px;
  font-size: 15px;
  color: #444;
}
</style> 